package okl.tdf.app.model
{
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	
	import okl.tdf.app.controller.messages.FeedResultMessage;
	import okl.tdf.app.model.vo.SampleRequest;
	import okl.tdf.model.InteractionsPerCountry;

	/**
	 *  Model for InteractionDisplayView
	 * 
	 *  @see okl.tdf.app.components.InteractionDisplayView
	 *	@author "oleksandr.kulinchenko@gmail.com"
	 * 
	 */
	public class InteractionDisplayModel
	{
		public function InteractionDisplayModel()
		{
		}
		
		/**
		 * Shared model
		 */
		[Inject][Bindable]
		public var appModel:AppModel;
		
		private var _dataLookupMap:Dictionary;
		
		//{region CLASS_INTERFACE
		[Bindable]public var iteractionsData:ArrayCollection;
		[Bindable]public var firstResult:InteractionsPerCountry;
		[Bindable]public var lastResult:InteractionsPerCountry;			
		//}endregion
		
		/**
		 * Process TDF VO, creates iteractionsData for component and lookupMap
		 */
		[MessageHandler]public function processSampleRequest(message:FeedResultMessage):void{
			if(!message.subscribed){//guard clause to process unsubscribe and invalidate component
				iteractionsData=null;
				firstResult=lastResult=null;
				return;
			}
			
 			iteractionsData = iteractionsData || new ArrayCollection();
			_dataLookupMap = _dataLookupMap || new Dictionary();
			
			var iteractionsDataItem:SampleRequest = message.result;
			
			var targetInteraction:InteractionsPerCountry = _dataLookupMap[iteractionsDataItem.country] as InteractionsPerCountry;
			if(targetInteraction==null){
				targetInteraction = new InteractionsPerCountry(iteractionsDataItem.country);
				targetInteraction.firstResultTime=iteractionsDataItem.timestamp;					
				//save in datastructures for display and lookup
				_dataLookupMap[targetInteraction.countryCode]=targetInteraction;
				iteractionsData.addItem(targetInteraction);
			}else{
				targetInteraction.totalCount++;			
			}
			targetInteraction.lastResultTime=iteractionsDataItem.timestamp;
			
			if(firstResult==null){
				firstResult=targetInteraction;
			}
			lastResult=targetInteraction;	
			
			appModel.feedState = AppModel.STATE_ACTIVE;
		}
		

	}	
}